const path = require("path");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const webpack = require("webpack");
const {BundleAnalyzerPlugin} = require("webpack-bundle-analyzer");
const {getStyleLoaders,splitChunks,getUrlLoader,tsLoader} = require("../utils");
let isDev = process.env.NODE_ENV == "development" ? true : false;

// lib打包配置区
const libraryName = "lib_framework";//不要取去掉【lib_】dev-server的express会根据路径取值
const {distPath,basePath} = require("../config");
const libraryPath = path.resolve(distPath, libraryName);
const dllPath = path.resolve(distPath, "dll");
const entryPath = path.resolve(__dirname,"../../framework/index.js");
const moduleRegex = /node_modules/;

module.exports = {
  entry: {
    index: entryPath
  },
  output: {
    path: libraryPath,
    filename: "[name].js",
    chunkFilename:isDev?"[name].js":"[name].[contenthash:8].js",
    library: libraryName,
    libraryTarget: "umd",
    libraryExport: "",//default
    globalObject: "this",
    publicPath:basePath + libraryName + "/"
  },
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "../../"),
      "~": path.resolve(__dirname, "../../node_modules"),
    },
    extensions: [".jsx", ".js", ".tsx", ".ts", ".json"],
  },
  optimization: {
    splitChunks,
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: moduleRegex, // js处理排除node_modules和libs
        use: ["babel-loader"],
      },
      {
        test: /\.tsx?$/,
        exclude: moduleRegex, // js处理排除node_modules和libs
        use: ['babel-loader',tsLoader],
      },
      {
        // 源码就转语法树
        test: /\.css$/,
        exclude: moduleRegex,
        use: getStyleLoaders(true),
      },
      {
        // 三方样式就不转语法树
        test: /\.css$/,
        include: moduleRegex,
        use: getStyleLoaders(false),
      },
      {
        test: /\.less$/, // less只在源码里面写，三方包就用css避免重复打包
        exclude: moduleRegex,
        use: getStyleLoaders(true, {}, "less-loader"),
      },
      {
        test: /\.(jpg|png|gif|jpeg)$/, //处理图片,把图片打包到输出目录中
        loader:getUrlLoader()
      },
      {
        test:/\.svg(\?v=\d+\.\d+\.\d+)?$/,
        loader:getUrlLoader(true)
      }
    ],
  },
  plugins: [
    new CleanWebpackPlugin(),
    new webpack.DllReferencePlugin({
      manifest: require(path.join(dllPath, "react_manifest.json"))
    }),
    new MiniCssExtractPlugin({
      filename: isDev?"[name].css":"[name].[hash:8].css", 
      chunkFilename: isDev?"[name].css":"[name].[contenthash:8].css",
      ignoreOrder: true
    }),
    // new BundleAnalyzerPlugin({
    //   openAnalyzer:false
    // })
  ],
  performance: {
    maxAssetSize: 2 * 1024 * 1024, //默认值：250000 (bytes)
    maxEntrypointSize: 2 * 1024 * 1024
  },
  // stats:"minimal" // normal  minimal
};
